//
//  YWAttachmentManager.m
//  maintain
//
//  Created by Kyo on 16/3/18.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWAttachmentManager.h"
#import "YWDBTool.h"
#import "YWCommonTool.h"
#import "YWAliyunOSSManager.h"
#import "YWResourceManager.h"

@implementation YWAttachmentManager
YWSingletonM(Manager)


- (BOOL)updateAttachmentWithAttachments:(NSArray*)attachments{
    return [[YWDBTool shareDBTool] updateAttachmentWithAttachments:attachments];
}

- (BOOL)updateAttachmenLocalNameWithAttachment:(YWattachment*)attachment{
    return [[YWDBTool shareDBTool] updateAttachmenLocalNameWithAttachment:attachment];
}
-(NSArray *)attachmentWithRecordId:(NSInteger)recordId andType:(YWattachmentType)type{
    return [[YWDBTool shareDBTool] attachmentWithRecordId:recordId andType:type];
}

- (void)downloadFile:(NSString*)objectKey toFilePath:(NSString*)path progressBlock:(void (^)(float progress))progressBlock completeBlock:(void (^)(BOOL success))completeBlock{
    [[YWAliyunOSSManager shareManager] downloadFile:objectKey toFilePath:path progressBlock:^(float progress) {
        if (progressBlock) {
            progressBlock(progress);
        }
    } completeBlock:^(BOOL success) {
        NSString *typeName = [[path componentsSeparatedByString:@"."] lastObject];
        if ([typeName compare:@"txt" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            [self handleTxtFileWithPath:path];
        }
        if (completeBlock) {
            completeBlock(success);
        }
    }];
}
- (void)handleTxtFileWithPath:(NSString *)path{
    //处理txt格式内容显示有乱码的情况
    NSData *fileData = [NSData dataWithContentsOfFile:path];
    //判断是UNICODE编码
    NSString *isUNICODE = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
    //还是ANSI编码（-2147483623，-2147482591，-2147482062，-2147481296）encoding 任选一个就可以了
    NSString *isANSI = [[NSString alloc] initWithData:fileData encoding:-2147483623];
    if (isUNICODE) {
        NSString *retStr = [[NSString alloc]initWithCString:[isUNICODE UTF8String] encoding:NSUTF8StringEncoding];
        NSData *data = [retStr dataUsingEncoding:NSUTF16StringEncoding];
        [data writeToFile:path atomically:YES];
    }
    else if(isANSI){
        NSData *data = [isANSI dataUsingEncoding:NSUTF16StringEncoding];
        [data writeToFile:path atomically:YES];
    }
    //    return [NSURL fileURLWithPath:path];
}
@end
